<?php

namespace App\Services\Strator;

use App\Models\Strator\StratorDepartment;
use App\Models\Strator\StratorHasPosition;
use App\Models\Strator\StratorPermission;
use App\Models\Strator\StratorPosition;
use Illuminate\Support\Collection;

class StratorDepartmentService
{

    //
    public function getStratorDepartments($strator): array{
        $department_ids=$this->getDirectDepartmentIds($strator);
        $stratorDepartments=StratorDepartment::with(['positions','parent'])
            // ->whereIn('id',$department_ids)
            ->orderBy('sort','asc')
            ->get()
            ->toArray();
        foreach ($stratorDepartments as $key=>$department){
            $stratorDepartments[$key]['children']=$this->getStratorDepartmentsByPid($department['id']);
        }
        return $stratorDepartments;
    }

    //
    public function getDirectDepartmentIds($strator): Collection{
        if($strator->is_super==1){
            return StratorDepartment::where('pid',0)->pluck('id');
        }
        return $strator->positions()->pluck('department_id');
    }

    //
    public function getStratorDepartmentsByPid($pid): array{
        $children=StratorDepartment::with(['positions','parent'])->where('pid',$pid)
            ->orderBy('sort','asc')
            ->get()->toArray();
        foreach ($children as $key=>$department){
            $children[$key]['children']=$this->getStratorDepartmentsByPid($department['id']);
        }
        return $children;
    }

    //
    public function getAuthDepartmentIds($strator):Collection{
        if($strator->is_super==1){
            return StratorDepartment::pluck('id');
        }
        $department_ids = $strator->positions()->pluck('department_id');
        foreach ($department_ids as $department_id){
            $department_ids=$department_ids->merge($this->getDepartmentIdsByPid($department_id));
        }
        return $department_ids;
    }
    //
    public function getDepartmentIdsByPid($pid): Collection{
        $childrenIds=StratorDepartment::where('pid',$pid)->pluck('id');
        foreach ($childrenIds as $key=>$department_id){
            $childrenIds=$childrenIds->merge($this->getDepartmentIdsByPid($department_id));
        }
        return $childrenIds;
    }

}
